package com.tianyu.jty.system.web;

import com.tianyu.jty.common.persistence.Page;
import com.tianyu.jty.common.persistence.PropertyFilter;
import com.tianyu.jty.common.web.BaseController;
import com.tianyu.jty.system.entity.SystemConfig;
import com.tianyu.jty.system.service.SystemConfigService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 系统配置项controller
 * @author ty
 * @date 2017年12月23日
 */
@Controller
@RequestMapping("system/config")
public class SystemConfigController extends BaseController{
	
	@Autowired
	private SystemConfigService systemConfigService;
	
	/**
	 * 默认页面
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "system/configList";
	}

	/**
	 * 获取字典json
	 */
	@RequiresPermissions("sys:config:view")
	@RequestMapping(value="json",method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> configList(HttpServletRequest request) {
		Page<SystemConfig> page = getPage(request);
		List<PropertyFilter> filters = PropertyFilter.buildFromHttpRequest(request);
		page = systemConfigService.search(page, filters);
		return getEasyUIData(page);
	}

	/**
	 * 修改字典跳转
	 * 
	 * @param configName
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:config:update")
	@RequestMapping(value = "update/{configName}", method = RequestMethod.GET)
	public String updateForm(@PathVariable("configName") String configName, Model model) {
		model.addAttribute("config", systemConfigService.get(configName));
		model.addAttribute("action", "update");
		return "system/configForm";
	}

	/**
	 * 修改字典
	 * 
	 * @param config 系统配置项Bean
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:config:update")
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	public String update(@Valid @ModelAttribute @RequestBody SystemConfig config,Model model) {
		systemConfigService.update(config);
		return "success";
	}
	
	@ModelAttribute
	public void getDict(@RequestParam(value = "configName", defaultValue = "-1") String configName,Model model) {
		if (configName != null) {
			model.addAttribute("config", systemConfigService.get(configName));
		}
	}

}
